import { getUserSelf, changeUser } from "@/api/admin/user.js";
import { getAll } from "@/api/admin/main.js";

function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        var prop = initalObj[i];
        // 避免相互引用对象导致死循环，如initalObj.a = initalObj的情况
        if (prop === obj) {
            continue;
        }
        if (typeof prop === "object" && prop != null) {
            obj[i] = prop.constructor === Array ? [] : Object.create(prop);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}

const state = {
    user: {},
    ruleForm: {
        gender: "UNKNOWN",
    },
}

const getters = {

}

const mutations = {
    GET_USER(state, { data }) {
        state.user = deepClone(data);
        state.ruleForm = deepClone(data);
    },
}

const actions = {
    //获取用户信息
    getUser({ commit }) {
        return new Promise((resolve, reject) => {
            getUserSelf()
                .then(response => {
                    const { data } = response;
                    commit('GET_USER', { data });
                    resolve();
                })
                .catch(error => {
                    reject(error);
                })
        })
    },
    //修改用户
    change_User({ commit }, { id, ruleForm }) {
        return new Promise((resolve, reject) => {
            changeUser(id, ruleForm)
                .then((response) => {
                    const { status } = response;
                    resolve(status);
                })
                .catch(error => {
                    reject(error);
                })
        })
    },
    //获取全部数据
    get_All() {
        return new Promise((resolve, reject) => {
            getAll()
                .then((response) => {
                    const { data } = response;
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                })
        })
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}